#include <stdio.h>
#include <string.h>

// 定义base64字符集
static const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

// 将一个字节转换为base64编码
static char base64_encode(unsigned char c) {
    return base64_chars[c];
}

// 将一个base64编码转换为字节
static unsigned char base64_decode(char c) {
    if (c >= 'A' && c <= 'Z') {
        return c - 'A';
    } else if (c >= 'a' && c <= 'z') {
        return c - 'a' + 26;
    } else if (c >= '0' && c <= '9') {
        return c - '0' + 52;
    } else if (c == '+') {
        return 62;
    } else if (c == '/') {
        return 63;
    } else {
        return 0; // 非法字符
    }
}

// 将一个二进制数组进行base64编码
void base64_encode_binary(const unsigned char *input, int input_len, char *output) 
{
    int i, j;
    for (i = 0, j = 0; i < input_len; i += 3, j += 4) {
        unsigned char a = input[i];
        unsigned char b = (i + 1 < input_len) ? input[i + 1] : 0;
        unsigned char c = (i + 2 < input_len) ? input[i + 2] : 0;
        output[j] = base64_encode((a >> 2) & 0x3F);
        output[j + 1] = base64_encode(((a << 4) | (b >> 4)) & 0x3F);
        output[j + 2] = (i + 1 < input_len) ? base64_encode(((b << 2) | (c >> 6)) & 0x3F) : '=';
        output[j + 3] = (i + 2 < input_len) ? base64_encode(c & 0x3F) : '=';
    }
    output[j] = '\0'; // 添加字符串结束符
}

// 将一个base64编码的字符串解码为原始二进制数组
void base64_decode_binary(const char *input, int input_len, unsigned char *output) 
{
    int i, j;
    for (i = 0, j = 0; i < input_len; i += 4, j += 3) {
        unsigned char a = base64_decode(input[i]);
        unsigned char b = base64_decode(input[i + 1]);
        unsigned char c = base64_decode(input[i + 2]);
        unsigned char d = base64_decode(input[i + 3]);
        output[j] = (a << 2) | (b >> 4);
        output[j + 1] = (b << 4) | (c >> 2);
        output[j + 2] = (c << 6) | d;
    }
}
